package com.wechat.servlet.Relation;

import com.alibaba.fastjson.JSONArray;
import com.wechat.DAO.DaoImpl.UserRelationDAOIpml;
import com.wechat.DAO.UserRelationDAO;
import com.wechat.pojo.UserRelation;
import com.wechat.servlet.Utils.Base64Encoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class GetRelationServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String UID=request.getParameter("username");
        UserRelationDAO userRelationDAO = new UserRelationDAOIpml();
        List<UserRelation> userRelations = null;
        try {
            userRelations = new ArrayList<>();
            userRelations = userRelationDAO.getAllRelation(UID);
        }catch (Exception e){
            e.printStackTrace();
            response.getWriter().write("fail");
            return;
        }
        if(userRelations!=null && !userRelations.isEmpty()){
            JSONArray jsonArray = (JSONArray) JSONArray.toJSON(userRelations);
            String json = jsonArray.toString();
            String base64 = Base64Encoder.encode(json);
            response.getWriter().write(base64);
        }else {
            response.getWriter().write("fail");
        }
    }
}
